﻿using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using bpms.Enums;
using bpms.Models;

namespace bpms.Controllers
{
    /// <summary>
    /// 基础控制器
    /// </summary>
    public class BaseController : Controller
    {
        protected CurrentUserInfo CurrentUser => GetCurrentUserInfo();

        private CurrentUserInfo GetCurrentUserInfo()
        {
            var user = HttpContext.User; // 正确访问实例属性
            if (user?.Identity?.IsAuthenticated != true)
                return new CurrentUserInfo { IsAuthenticated = false };

            return new CurrentUserInfo
            {
                Id = GetUserId(user),
                Name = user.FindFirstValue(ClaimTypes.Name),
                Role = user.FindFirstValue(ClaimTypes.Role),
                UserType = GetUserType(user),
                IsAuthenticated = true
            };
        }

        private static int GetUserId(ClaimsPrincipal user)
        {
            var value = user.FindFirstValue(ClaimTypes.NameIdentifier);
            return int.TryParse(value, out int id) ? id : -1;
        }

        private static UserType GetUserType(ClaimsPrincipal user)
        {
            var value = user.FindFirstValue("UserType");
            return Enum.TryParse<UserType>(value, out var type) ? type : UserType.Admin;
        }
    }
}
